package demo.practice.competition;

import java.util.Stack;

public class P5782 {

    public long maxAlternatingSum(int[] nums) {

        Stack<Integer> stack = new Stack<>();

        long max = 0;
        long min = 0;

        long res = 0;
        for (int i = 0; i < nums.length; i++) {

            if (stack.size() == 0) {
                max = nums[i];
                stack.add(nums[i]);
            } else if (stack.peek() > nums[i]) {
                stack.add(nums[i]);
                min = nums[i];
            } else if (stack.peek() == nums[i]) {
                //什么也不做，加到stack中不会产生影响if()
            } else if (stack.peek() < nums[i]) {
                if (min == 0) {
                    //说明没有产生更小的值
                    stack.add(nums[i]);
                    max = nums[i];
                } else {
                    res += (max - min);
                    max = nums[i];
                    min = 0;
                    stack.clear();
                    stack.add(nums[i]);
                }
            }
        }
        return res+max;
    }
}
